package org.itboys.mobile.controller.mobile.order;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mdl.util.MobileSignUtils;
import org.itboys.mobile.dto.order.MdlOrderDto;
import org.itboys.mobile.service.mysql.mobile.order.MdlMobileOrderService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zzq
 * 时间：2017/12/5
 * 描述：迈迪龙_手机_订单
 */
@Controller
@RequestMapping("/mdl/mobile/order")
@Api(value = "order", description = "订单")
public class MdlMobileOrderController extends BaseController {
    @Autowired
    private MdlMobileOrderService orderService;

    /**
     * 创建订单
     */
    @RequestMapping(value = "/createOrder", method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】创建订单。")
    public void createOrder(HttpServletRequest request,
                            HttpServletResponse response,
                            @ApiParam(required = true, name = "cartIds", value = "购物车ID集合(非商品ID)") @RequestParam(value = "cartIds", required = true) List<Long> cartIds,
                            @ApiParam(required = true, name = "addressId", value = "收货地址Id。") @RequestParam(value = "addressId", required = false) Long addressId,
                            @ApiParam(required = false, name = "sendType", value = "配送类型") @RequestParam(value = "sendType", required = false) Integer sendType,
                            @ApiParam(required = false, name = "remark", value = "订单备注。") @RequestParam(value = "remark", required = false) String remark,
                            @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                            @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
    ) {
        try {

            //2017年6月20日，新增，验证签名
            Map<String, Object> param = new HashMap<String, Object>();
            StringBuilder cartIdsStr = new StringBuilder();
            for (Long cartId : cartIds) {
                cartIdsStr.append(cartId + ",");
            }
            param.put("cartIds", cartIdsStr.substring(0, cartIdsStr.length() - 1).toString());//实际是字符串。cartIds=1,2,3
            param.put("addressId", addressId);
            param.put("sendType", sendType);
            param.put("remark", remark);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if (!signSer) {
                logger.warn("签名校验失败");
                ResponseMessage.error(-1, "签名校验失败");
                return;
            }

            Long memberId = AccountIdHoldUtils.getMemberId();
            Map<String, Object> result = orderService.createOrder(memberId, cartIds,
                    addressId, sendType, remark);
            ResponseMessage.success(result);
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/mdl/mobile/order/createOrder----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    /**
     * 销售员通过pad创建订单
     *
     * @param request
     * @param response
     * @param cartIds
     * @param nickName
     * @param mobile
     * @param address
     * @param sendType
     * @param remark
     * @param nonce
     * @param sign
     */
    @RequestMapping(value = "/createOrderPad", method = RequestMethod.POST)
    @ApiOperation(value = "【用户版】创建订单。")
    public void createOrderPad(HttpServletRequest request,
                               HttpServletResponse response,
                               @ApiParam(required = true, name = "cartIds", value = "购物车ID集合(非商品ID)") @RequestParam(value = "cartIds", required = true) List<Long> cartIds,
                               @ApiParam(required = true, name = "nickName", value = "用户名称") @RequestParam(value = "nickName", required = true) String nickName,
                               @ApiParam(required = true, name = "mobile", value = "用户手机号") @RequestParam(value = "mobile", required = true) String mobile,
                               @ApiParam(required = true, name = "code", value = "手机验证码") @RequestParam(value = "code", required = true) String code,
                               @ApiParam(required = true, name = "address", value = "收货地址") @RequestParam(value = "address", required = true) String address,
                               @ApiParam(required = false, name = "sendType", value = "配送类型") @RequestParam(value = "sendType", required = false) Integer sendType,
                               @ApiParam(required = false, name = "remark", value = "订单备注。") @RequestParam(value = "remark", required = false) String remark,
                               @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                               @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
    ) {
        try {

            //2017年6月20日，新增，验证签名
            Map<String, Object> param = new HashMap<String, Object>();
            StringBuilder cartIdsStr = new StringBuilder();
            for (Long cartId : cartIds) {
                cartIdsStr.append(cartId + ",");
            }
            param.put("cartIds", cartIdsStr.substring(0, cartIdsStr.length() - 1).toString());//实际是字符串。cartIds=1,2,3
            param.put("nickName", nickName);
            param.put("mobile", mobile);
            param.put("code", code);
            param.put("sendType", sendType);
            param.put("address", address);
            param.put("remark", remark);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if (!signSer) {
                logger.warn("签名校验失败");
                ResponseMessage.error(-1, "签名校验失败");
                return;
            }

            Long memberId = AccountIdHoldUtils.getMemberId();
            Map<String, Object> result = orderService.createOrderPad(memberId, cartIds, sendType, nickName, mobile, code, address, remark);
            ResponseMessage.success(result);
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code1 = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code1 = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/mdl/mobile/order/createOrderPad----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code1, msg);
        }
    }

    /**
     * 分页获取订单
     *
     * @param request
     * @param response
     * @param type
     * @param orderStatuses
     * @param createTime_start
     * @param createTime_end
     * @param pageSize
     * @param pageNumber
     * @param sort
     * @param order
     * @param nonce
     * @param sign
     */
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】分页获取订单。")
    public void select(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required = true, name = "type", value = "订单类型。1,代理商采购订单，2待定，3，商城订单") @RequestParam(value = "type", required = true) Integer type,
                       @ApiParam(required = true, name = "orderStatuses", value = "订单状态集合，支持传入多个状态。例如：orderStatuses=1,2,3" +
                               "0全部，1，待付款，2待配送，3配送中，4待评价，5已评价，6待退款， 7已退款，8待退货，9已退货,10已取消") @RequestParam(value = "orderStatuses", required = true) List<Integer> orderStatuses,
                       @ApiParam(required = false, name = "createTime_start", value = "查询参数。开始时间。默认为空") @RequestParam(value = "createTime_start", required = false) String createTime_start,
                       @ApiParam(required = false, name = "createTime_end", value = "查询参数。结束时间。默认为空") @RequestParam(value = "createTime_end", required = false) String createTime_end,
                       @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
                       @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
                       @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
                       @ApiParam(required = false, name = "order", value = "排序参数。。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
                       @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
    ) {
        try {
            Long memberId = AccountIdHoldUtils.getMemberId();
            memberId = 12L;
            List<MdlOrderDto> result = orderService.selectOrder(request, memberId, type, orderStatuses);
            ResponseMessage.success(result);
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/mdl/mobile/order/select----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    /**
     * 查询单个
     *
     * @param request
     * @param response
     * @param orderId
     * @param nonce
     * @param sign
     */
    @RequestMapping(value = "/findOne", method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】查看订单详情。")
    public void findOne(HttpServletRequest request,
                        HttpServletResponse response,
                        @ApiParam(required = true, name = "orderId", value = "订单Id") @RequestParam(value = "orderId", required = true) Long orderId,
                        @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
    ) {
        try {
            Long memberId = AccountIdHoldUtils.getMemberId();
            MdlOrderDto result = orderService.findOne(orderId, memberId);
            ResponseMessage.success(result);
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/mdl/mobile/order/findOne----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    /**
     * 取消订单
     *
     * @param request
     * @param response
     * @param orderId
     * @param nonce
     * @param sign
     */
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】取消订单。1 采购订单  待付款才能取消，3用户商城订单，待付款才能取消。")
    public void cancel(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                       @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
    ) {
        try {
            //2017年6月20日，新增，验证签名
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("orderId", orderId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if (!signSer) {
                logger.warn("签名校验失败");
                ResponseMessage.error(-1, "签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.cancelOrder(orderId, memberId);
            ResponseMessage.success();
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/mdl/mobile/order/cancel----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    /**
     * 代理商确认收款
     * @param request
     * @param response
     * @param orderId
     * @param confirmMessage
     * @param nonce
     * @param sign
     */
    @RequestMapping(value="/confirm",method= RequestMethod.POST)
    @ApiOperation(value="【管理版】确认订单。代理商确认收款 待付款才能确认")
    public void confirm(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                        @ApiParam(required = true, name = "confirmMessage", value = "确认信息") @RequestParam(value = "confirmMessage", required = true) String confirmMessage,
                       @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            //2017年6月20日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            orderService.confirmOrder(orderId,confirmMessage);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/mdl/mobile/order/cancel----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    /**
     * 配送订单
     *
     * @param request
     * @param response
     * @param orderId
     * @param nonce
     * @param sign
     */
    @RequestMapping(value = "/sendOrder", method = RequestMethod.POST)
    @ApiOperation(value = "【管理版】配送订单。orderStatus==2才能配送。")
    public void sendOrder(HttpServletRequest request,
                          HttpServletResponse response,
                          @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,

                          @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                          @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
    ) {
        try {
            //2017年6月20日，新增，验证签名
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("orderId", orderId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if (!signSer) {
                logger.warn("签名校验失败");
                ResponseMessage.error(-1, "签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.sendOrder(orderId);
            ResponseMessage.success();
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/mdl/mobile/order/sendOrder----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    /**
     * 确认订单
     *
     * @param request
     * @param response
     * @param orderId
     * @param nonce
     * @param sign
     */
    @RequestMapping(value = "/confirmReceive", method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】确认收货。配送中订单才能确认收货，不区分订单类型。")
    public void confirmReceive(HttpServletRequest request,
                               HttpServletResponse response,
                               @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                               @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                               @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
    ) {

        try {
            //2017年6月20日，新增，验证签名
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("orderId", orderId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if (!signSer) {
                logger.warn("签名校验失败");
                ResponseMessage.error(-1, "签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.confirmReceive(orderId, memberId);
            ResponseMessage.success();
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;

            } else {
                logger.error("/mdl/mobile/order/confirmReceive----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    /**
     * 评论订单
     *
     * @param request
     * @param response
     * @param orderId
     * @param productIds
     * @param contents
     * @param scores
     * @param images
     * @param nonce
     * @param sign
     */
    @RequestMapping(value = "/comment", method = RequestMethod.POST)
    @ApiOperation(value = "【用户版和管理版】评论订单，每个商品最大传入三张图片，没有图片的评论，用noImage字符串，固定images集合占位。")
    public void comment(HttpServletRequest request,
                        HttpServletResponse response,
                        @ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam(value = "orderId", required = true) Long orderId,
                        @ApiParam(required = true, name = "productIds", value = "商品ID集合(productIds,contents,scores大小，顺序对应)。例如：productIds=1,2,3") @RequestParam(value = "productIds", required = true) List<Long> productIds,
                        @ApiParam(required = true, name = "contents", value = "评论内容集合，默认值：系统默认好评。(productIds,contents,scores大小，顺序对应)。例如：contents=1,2,3") @RequestParam(value = "contents", required = true) List<String> contents,
                        @ApiParam(required = true, name = "scores", value = "评分(0-5)集合。默认值：5。（productIds,contents,scores大小，顺序对应）。例如：scores=1,2,3") @RequestParam(value = "scores", required = true) List<Integer> scores,
                        @ApiParam(required = true, name = "images", value = "图片集合；，固定大小=productIds集合大小*3。每个商品限制最大传入三张，没有图片的使用noImage字符传固定值，在集合中占位") @RequestParam(value = "images", required = true) List<String> images,
                        @ApiParam(value = "随机数") @RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign
    ) {
        try {
            //2017年6月20日，新增，验证签名
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("orderId", orderId);
            StringBuilder productIdsStr = new StringBuilder();
            for (Long productId : productIds) {
                productIdsStr.append(productId + ",");
            }
            param.put("productIds", productIdsStr.substring(0, productIdsStr.length() - 1).toString());//实际是字符串。cartIds=1,2,3
            StringBuilder contentsStr = new StringBuilder();
            for (String content : contents) {
                contentsStr.append(content + ",");
            }
            param.put("contents", contentsStr.substring(0, contentsStr.length() - 1).toString());
            StringBuilder scoresStr = new StringBuilder();
            for (Integer score : scores) {
                scoresStr.append(score + ",");
            }
            param.put("scores", scoresStr.substring(0, scoresStr.length() - 1).toString());
            StringBuilder imagesStr = new StringBuilder();
            for (String image : images) {
                imagesStr.append(image + ",");
            }
            param.put("images", imagesStr.substring(0, imagesStr.length() - 1).toString());

            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if (!signSer) {
                logger.warn("签名校验失败");
                ResponseMessage.error(-1, "签名校验失败");
                return;
            }

            Long memberId = AccountIdHoldUtils.getMemberId();
            orderService.commentOrder(orderId, productIds, contents, scores, images, memberId);
            ResponseMessage.success();
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/mdl/mobile/order/comment----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

}
